package com.starsea.book.ui.newpage

import android.os.Bundle
import android.view.View
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.starsea.book.R
import com.starsea.book.base.VMBaseFragment
import com.starsea.book.databinding.FragmentHomeCategoryChildBinding
import com.starsea.book.ui.newpage.adapter.CategoryParentAdapter
import com.starsea.book.ui.newpage.viewmodel.HomeViewModel
import com.starsea.book.utils.LogUtils
import com.starsea.book.utils.gone
import com.starsea.book.utils.startActivity
import com.starsea.book.utils.toastOnUi
import com.starsea.book.utils.viewbindingdelegate.viewBinding

/**
 * @author Lee
 * @createTime 2024-01-10 21 GMT+8
 * @desc :
 */
class CategoryChildFragment : VMBaseFragment<HomeViewModel>(R.layout.fragment_home_category_child) {
    private val binding by viewBinding(FragmentHomeCategoryChildBinding::bind)
    override val viewModel by viewModels<HomeViewModel>()
    var type = 1

    lateinit var mAdapter: CategoryParentAdapter

    companion object {
        fun newInstance(type: Int): CategoryChildFragment {
            val args = Bundle()
            val fragment = CategoryChildFragment()
            args.putInt("type", type)
            fragment.arguments = args
            return fragment
        }
    }

    override fun onFragmentCreated(view: View, savedInstanceState: Bundle?) {

        type = requireArguments().getInt("type", 1)

        LogUtils.e(">>>> ", "type = " + type)

        viewModel.category(type)

        mAdapter = CategoryParentAdapter(requireContext()) {
            startActivity<CategoryDetailsActivity> {
                putExtra("typeTitle", it.typeTitle ?: "")
                putExtra("typeId", it.typeId)
            }
        }

        binding.rvContent.adapter = mAdapter

        binding.rvContent.layoutManager = LinearLayoutManager(requireContext())

        binding.refreshLayout.setOnRefreshListener {
            viewModel.category(type)
        }

        viewModel.dataCategoryResult.observe(this) {
            binding.refreshLayout.isRefreshing = false
            if (it.status != 200) {
                toastOnUi(it.msg)
            } else if (it.status == 401) {
                toastOnUi("登录过期,请重新登录")
                LoginActivity.start(requireContext())
            } else {
                binding.tvEmptyMsg.gone(!it.data.isNullOrEmpty())
                mAdapter.setItems(it.data)
            }
        }
    }
}